package com.kwq.shixi.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

/**
 * 字符串工具类
 *
 * @author zengpeng
 * @date May 30, 2019
 */
public class FileUtil {
	/**
	 * 将本地图片转换成Base64编码字符串
	 *
	 * @param imgFile 图片目录路径
	 * @return
	 */
	public static String getImgFileToBase64(String imgFile) {
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream inputStream = null;
		byte[] buffer = null;
		// 读取图片字节数组
		try {
			inputStream = new FileInputStream(imgFile);
			int count = 0;
			while (count == 0) {
				count = inputStream.available();
			}
			buffer = new byte[count];
			inputStream.read(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					// 关闭inputStream流
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// 对字节数组Base64编码

		try {
			return new String(Base64.getMimeEncoder().encode(buffer), "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}


	/**
	 * 获取文件后缀的方法
	 *
	 * @param file 要获取文件后缀的文件
	 * @return 文件后缀
	 * @author https://www.4spaces.org/
	 */
	public static String getMultipartFileExtName(MultipartFile file) {
		String extension = "";
		try {
			if (file != null) {
				String name = file.getOriginalFilename();
				extension = name.substring(name.lastIndexOf("."));
			}
		} catch (Exception e) {
			extension = "";
		}
		return extension;
	}

}
